package com.example.firstapp.ContentProvider

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.ContextCompat.startActivity
import com.example.firstapp.R
import com.example.firstapp.databinding.ActivityContentProviderBinding
import com.example.firstapp.databinding.ActivityRequestPermissionsBinding

class requestPermissions : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_request_permissions)
        val binding  = ActivityRequestPermissionsBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.call.setOnClickListener {
            // checkSelfPermission判断用户是否授权(Context应用运行时的全局环境, 具体的权限名)
            // 返回PackageManager.PERMISSION_GRANTED代表已授权
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.CALL_PHONE
                ) != PackageManager.PERMISSION_GRANTED
            ) {// 返回值不等于，未授权
                // requestPermissions 申请授权
                // （参数1：Activity实例 参数2：权限名的String数组 参数3：请求码，要求唯一性）
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.CALL_PHONE), 1
                )
            } else {
                // 容易返回值等于，即已授权，直接拨打电话
                call()
            }
        }
    }
    // 不过是否申请成功，回调到此方法，授权的结果则会封装在grantResults参数中
    // 参数1：标识 参数2：权限列表 参数3：结果
    override fun onRequestPermissionsResult(requestCode: Int,
                                        permissions: Array<String>, grantResults: IntArray) {
        // 调用父方法
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
        // requestCode=1时
            1 -> {
                if (grantResults.isNotEmpty() &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED) { //有结果且结果为授权
                    call()
                } else {
                    Toast.makeText(this, "You denied the permission",
                        Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
    private fun call(){
        try {
            val intent = Intent(Intent.ACTION_CALL)
            intent.data = Uri.parse("tel:10086")
            startActivity(intent)
        } catch (e: SecurityException) {
            e.printStackTrace()
        }
    }
}